package day_02_02_JMM;

import lombok.Data;

import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author shihan
 * @Date 2020/11/21 17:23
 * @Version 1.0
 */
public class MyQuestionJMM2 {

    static Resource2 resource = new Resource2();

    /**
     *【JMM】
     * 线程操作共享内存数据，会将共享内存数据进行副本拷贝
     * 放到当前线程的工作空间中，当操作完成后再将最后的数据写回到共享内存中
     * @param args
     */
    public static void main(String[] args) {

        new Thread(new MyThread(resource),"A").start();
        new Thread(new MyThread(resource),"B").start();
        try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
        new Thread(new MyThread(resource),"C").start();

    }

}

@Data
class Resource2{
    int res = 10;

    public void add(){
        this.res = this.res + 10;
    }
}

class MyThread implements Runnable{

    private Resource2 resource;

    public MyThread(Resource2 resource2) {
        this.resource = resource2;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "\t before" + resource.getRes());  //10
        resource.add();
        System.out.println(Thread.currentThread().getName() + "\t after" + resource.getRes());  //20
    }
}
